package hz.mobileproject.pda.toolsmanager.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import hz.mobileproject.pda.R;
import hz.mobileproject.pda.app.MainApp;
import hz.mobileproject.pda.entity.response.Response_loadPoliceInfo;
import hz.mobileproject.pda.entity.response.Response_login_user;
import hz.mobileproject.pda.entity.response.Rp_loadPrisonerInfo;
import hz.mobileproject.pda.listener.CustomNetCallBack;
import hz.mobileproject.pda.network.Constance;
import hz.mobileproject.pda.toolsmanager.adapter.ToolsBianGengLVAdaper;
import hz.mobileproject.pda.toolsmanager.bean.request.RQ_ChangeStaion;
import hz.mobileproject.pda.toolsmanager.bean.request.RQ_SelByStaton;
import hz.mobileproject.pda.toolsmanager.bean.response.RP_StationInfo;
import hz.mobileproject.pda.toolsmanager.bean.response.RP_ToolInfo;
import hz.mobileproject.pda.toolsmanager.bean.response.RP_ToolSysSet;
import hz.mobileproject.pda.toolsmanager.bean.response.RQ_SelByStatonList;
import hz.mobileproject.pda.toolsmanager.utils.ToolCommonHttpUtils;
import hz.mobileproject.pda.ui.base.BaseScanActivity;
import hz.mobileproject.pda.utils.HttpRqUtils;

@ContentView(R.layout.activity_tools_change)
public class ToolChangeActivity extends BaseScanActivity {
    @ViewInject(R.id.lv_tools_change)
    private ListView lv_tools_change;
    @ViewInject(R.id.tv_caozuo_user)
    private TextView tv_caozuo_user;
    @ViewInject(R.id.tv_biangeng_user)
    private TextView tv_biangeng_user;
    @ViewInject(R.id.tv_gongwei)
    private TextView tv_gongwei;

    private ToolsBianGengLVAdaper adapter;
    private List<RQ_SelByStatonList.MyToolData> mToolDataList;


    private static final int REQUEST_CODE_POLICE = 0x1091;
    private static final int REQUEST_CODE_PRISONER = 0x1092;
    private static final int REQUEST_CODE_WORK_POSITION = 0x1093;
    private static final int REQUEST_CODE_TOOLS = 0x1094;

    //当前民警信息
    private Response_loadPoliceInfo mPoliceInfo;
    //当前扫码罪犯
    private Rp_loadPrisonerInfo mPrisoner;
    //当前扫描工位
    private RP_StationInfo mStation;

    private RP_ToolSysSet mToolSystemSet;
    private Gson mGson;



    @Override
    protected void initData(){
        setTitleText("工位变更");
//        List<RP_ToolInfo> toolsGrantList = new ArrayList<>();
        adapter = new ToolsBianGengLVAdaper(this,new ArrayList<RQ_SelByStatonList.MyToolData>());
        lv_tools_change.setAdapter(adapter);

        mToolSystemSet = (RP_ToolSysSet) getIntent().getSerializableExtra("key");
        mGson = new Gson();

        //扫描民警
        scanPolice();
    }

    @Override
    protected void onScanSucesess(int requestCode, String scanMsg) {
        LogUtils.e(scanMsg);
        switch (requestCode) {
            case REQUEST_CODE_POLICE:
                getPliceInfoFromSer(scanMsg);
                break;
            case REQUEST_CODE_PRISONER:   //扫描变更人（即罪犯）
                getPrisonerInfoFromSer(scanMsg);
                break;
            case REQUEST_CODE_WORK_POSITION:    //扫描工位
                getWorkPositionInfoFromSer(scanMsg);
                break;
            case REQUEST_CODE_TOOLS:   //扫描工具
                getToolInfoFromSer(scanMsg);
                break;
        }
    }


    @Event({R.id.btn_gongwei_next, R.id.btn_gognwei_complete})
    private void onViewClick(View v){
        switch (v.getId()) {
            case R.id.btn_gongwei_next:
                modifyToolStatus(R.id.btn_gongwei_next);
                break;
            case R.id.btn_gognwei_complete:
                modifyToolStatus(R.id.btn_gognwei_complete);
                break;
        }
    }

    /**
     * 请求网络接口提交变更
     */
    private void modifyToolStatus(final int viewID) {
        if(mPoliceInfo == null){
            ToastUtils.showLong("请先获取操作人信息");
            return;
        }
        switch (mToolSystemSet.getGive_object()){
            case RP_ToolSysSet.TSS_GIVE_OBJECT_WORKPOSITION:
                if(mStation == null){
                    ToastUtils.showLong("请先获取工位信息");
                    return;
                }
                break;
        }
        if(mPrisoner == null) {
            ToastUtils.showLong("请先获取变更人信息");
            return;
        }


        if(adapter.getScanList().size() != mToolDataList.size()){
            ToastUtils.showLong("请先扫描完毕工位下的变更工具");
            return;
        }

        RQ_ChangeStaion rq_changeStaion = new RQ_ChangeStaion();
        rq_changeStaion.cus_number = mPoliceInfo.getCus_number() + "";
        rq_changeStaion.station_id = mStation.getStation_id();
        rq_changeStaion.station_name = mStation.getStation_name();
        rq_changeStaion.dprt_id = mPoliceInfo.getDepartment_id() + "";
        rq_changeStaion.dprt_name = mPoliceInfo.getDepartment_name();
        rq_changeStaion.change_user_id = mPrisoner.getPrisoner_id();
        rq_changeStaion.change_user_name = mPrisoner.getPrisoner_name();
        rq_changeStaion.updt_user_id = mPoliceInfo.getPolice_id();
        rq_changeStaion.updt_user_name = mPoliceInfo.getPolice_name();
        rq_changeStaion.updt_time = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        List<RQ_SelByStatonList.MyToolData> scanList = adapter.getScanList();
        int size = scanList.size();
        List<RQ_ChangeStaion.MyChangeStationTool> myChangeStationToolList = new ArrayList<>();
        RQ_ChangeStaion.MyChangeStationTool  myChangeStationTool = null;
        for(int i = 0; i < size;i++) {
            myChangeStationTool = new RQ_ChangeStaion.MyChangeStationTool();
            RQ_SelByStatonList.MyToolData myToolData = scanList.get(i);
            myChangeStationTool.tool_id = myToolData.tool_id;
            myChangeStationTool.tool_name = myToolData.tool_name;
            myChangeStationTool.tool_type = myToolData.tool_type;
            myChangeStationTool.record_type = "4";
            myChangeStationToolList.add(myChangeStationTool);
        }
        rq_changeStaion.tooldata = myChangeStationToolList;

        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_TOOL_CHANGE_STATION, rq_changeStaion, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                switch (viewID) {
                    case R.id.btn_gongwei_next:
                        ToastUtils.showLong("工位变更成功");
                        tv_caozuo_user.setText("");
                        mPrisoner = null;
                        tv_biangeng_user.setText("");
                        mStation = null;
                        adapter.deleteAll();
                        scanAfterPolice();

                        break;
                    case R.id.btn_gognwei_complete:
                        new AlertDialog.Builder(ToolChangeActivity.this).setTitle("提示")
                                .setMessage("变更提交成功，本页面将关闭")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        ToolChangeActivity.this.finish();
                                    }
                                }).setCancelable(false).create().show();
                        break;
                }
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("变更提交失败(" + rtnCode + "," + rtnMsg + ")");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("变更提交失败");
                LogUtils.e(ex);
            }
        });
    }


    /**
     * 请求网络接口获取民警信息
     *
     * @param scanStr
     */
    private void getPliceInfoFromSer(String scanStr) {
        ToolCommonHttpUtils.getPoliceInfoFromSer(scanStr, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                LogUtils.e(data);
                Response_loadPoliceInfo loadPoliceInfo = mGson.fromJson(data, Response_loadPoliceInfo.class);
                if (loadPoliceInfo == null) {
                    ToastUtils.showLong("民警信息为空");
                    return;
                }
                mScanLoadingDialog.dismiss();
                mPoliceInfo = loadPoliceInfo;
                //操作人
                tv_caozuo_user.setText(mPoliceInfo.getPolice_name());
                //打开扫描
                scanAfterPolice();
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("获取民警信息失败");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("获取民警信息失败");
                LogUtils.e(ex);
            }
        });
    }


    /**
     * 请求网络接口获取工位信息
     *
     * @param scanStr
     */
    private void getWorkPositionInfoFromSer(String scanStr) {
        ToolCommonHttpUtils.getWorkStationInfoFromSer(scanStr,mToolSystemSet,mPoliceInfo, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                LogUtils.e(data);
                RP_StationInfo stationInfo = mGson.fromJson(data, RP_StationInfo.class);
                if (stationInfo == null) {
                    ToastUtils.showLong("工位信息格式错误或为空");
                    return;
                }
                mScanLoadingDialog.dismiss();
                mStation = stationInfo;
                tv_gongwei.setText(stationInfo.getStation_name());

                getSelByStationList();
                scanAfterGongWei();
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("获取工位信息失败(" + rtnCode + "," + rtnMsg + ")");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("获取工位信息失败");
                LogUtils.e(ex);
            }
        });
    }

    /**
     * 请求网络接口获取工位下面工具信息
     */
    private void getSelByStationList() {
        RQ_SelByStaton rq_selByStaton = new RQ_SelByStaton(mPoliceInfo.getCus_number() + "",mStation.getStation_id());
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.TOOL_GONGWEI_SEL_BY_STATON, rq_selByStaton, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                RQ_SelByStatonList rq_selByStatonList = mGson.fromJson(data, RQ_SelByStatonList.class);
                mToolDataList = rq_selByStatonList.tooldata;
                adapter.clearAdd(mToolDataList);
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("获取工位列表失败");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("获取工位列表失败");
            }
        });
    }



    /**
     * 请求网络接口获取工具信息
     *
     * @param scanStr
     */
    private void getToolInfoFromSer(String scanStr) {
        ToolCommonHttpUtils.getToolInfoFromSer(scanStr,mToolSystemSet,mPoliceInfo, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                RP_ToolInfo toolInfo = mGson.fromJson(data, RP_ToolInfo.class);
                if (toolInfo == null) {
                    ToastUtils.showLong("工具信息格式错误或为空");
                    return;
                }
//                //判断工具是否报废
//                if(toolInfo.getStatus() == RP_ToolInfo.STATUS_SCRAP){
//                    ToastUtils.showLong("此工具已被报废");
//                    return;
//                }
//                //判断此工具是否变更
//                if (toolInfo.getSf_status() == RP_ToolInfo.SF_STATUS_GRANTED) {
//                    ToastUtils.showLong("此工具已被变更");
//                    return;
//                }
                //判断此工具是否在工位信息下面
                if(mToolDataList != null && mToolDataList.size() > 0) {
                    for (int i = 0; i < mToolDataList.size(); i++) {
                        if(toolInfo.getTool_id().equals(mToolDataList.get(i).tool_id)) {
                            adapter.setToolStatus(i,mToolDataList.get(i),true);
                            return;
                        }
                    }
                }

            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("获取工具信息失败(" + rtnCode + "," + rtnMsg + ")");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("获取工具信息失败");
                LogUtils.e(ex);
            }
        });
    }




    /**
     * 请求网络接口获取罪犯信息
     *
     * @param scanStr
     */
    private void getPrisonerInfoFromSer(String scanStr) {
        ToolCommonHttpUtils.getPrisonerInfoFromSer(scanStr, mPoliceInfo, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                LogUtils.e(data);
                Rp_loadPrisonerInfo loadPrisonerInfo = mGson.fromJson(data, Rp_loadPrisonerInfo.class);
                if (loadPrisonerInfo == null) {
                    ToastUtils.showLong("罪犯信息为空");
                    return;
                }
                mScanLoadingDialog.dismiss();
                mPrisoner = loadPrisonerInfo;
                tv_biangeng_user.setText(mPrisoner.getPrisoner_name());

                scanTools();
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("获取罪犯信息失败");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("获取罪犯信息失败");
                LogUtils.e(ex);
            }
        });
    }




    /**
     * ====================================扫描流程=========================================
     */
    private void scanPolice() {
        //是否需要扫描民警
        if (RP_ToolSysSet.TSS_CALL_TYPE_SCAN_USER == mToolSystemSet.getCall_type()) {
            //扫民警
            openScan(REQUEST_CODE_POLICE, mToolSystemSet, "请扫描民警条码");
        } else if (RP_ToolSysSet.TSS_CALL_TYPE_LOGIN_USER == mToolSystemSet.getCall_type()) {
            //使用登录民警信息
            mPoliceInfo = new Response_loadPoliceInfo();
            Response_login_user loginUser = MainApp.getInstance().getLoginUser();
            mPoliceInfo.setCus_number(loginUser.getCus_number());
            mPoliceInfo.setDepartment_id(loginUser.getDepartment_id());
            mPoliceInfo.setDepartment_name(loginUser.getDepartment_name());
            mPoliceInfo.setPolice_code(loginUser.getPolice_code());
            mPoliceInfo.setPolice_id(loginUser.getPolice_id());
            mPoliceInfo.setPolice_name(loginUser.getPolice_name());
            tv_caozuo_user.setText(mPoliceInfo.getPolice_name());
            //接着扫描
            scanAfterPolice();
        }
    }


    private void scanAfterPolice() {
        openScan(REQUEST_CODE_WORK_POSITION, mToolSystemSet, "请扫描工位");
    }

    private void scanAfterGongWei() {
        openScan(REQUEST_CODE_PRISONER, mToolSystemSet, "请扫描变更人");
    }

    private void scanTools() {
        //请扫描工具
        openScan(REQUEST_CODE_TOOLS, mToolSystemSet, "请扫描工具");
    }


}